import 'package:client_flutter_door/http/box.dart';
import 'package:client_flutter_door/http/door.dart';
import 'package:client_flutter_door/http/mongo.dart';
import 'package:client_flutter_door/model/door_model.dart';
import 'package:client_flutter_door/pages/panel.dart';
import 'package:client_flutter_door/pages/func.dart';
import 'package:client_flutter_door/utils/dt.dart';
import 'package:client_flutter_door/vars.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  // runApp(const MyApp());
  runApp(ChangeNotifierProvider(
    create: (context) => DoorModel(),
    child: const MyApp(),
  ));
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorKey: Vars.navigatorKey,
      title: '智能柜',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: const Color.fromARGB(255,13,110,253).withAlpha(30),),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: '智能柜'),
      // home: Text('测试'),
      // home: Test(),
    );
  }
}

class Test extends StatelessWidget {
  const Test({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        navigatorKey: Vars.navigatorKey,
        title: 'ces',
        home: Scaffold(
          key: Vars.scaffoldKey,
          appBar: AppBar(title: const Text('biaot ')),
          body: const Func(),
        ));
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  // List<Cabinet> boxs = [];

  late TabController _controller;

  List<Widget> list = const [
    Tab(text: '主控面板', icon: Icon(Icons.dashboard)),
    Tab(text: '功能界面', icon: Icon(Icons.apps)),
    Tab(text: '日志', icon: Icon(Icons.speaker_notes)),
    // Tab(text: '关于', icon: Icon(Icons.info)),
  ];

  @override
  void initState() {
    Door.login();
    super.initState();
    _controller = TabController(length: list.length, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: Vars.scaffoldKey,
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // title: Text(widget.title),
        toolbarHeight: 0,
        // title: ElevatedButton(
        //   child: Text('测试跳转'),
        //   onPressed: () {
        //     setState(() {
        //        _controller.index = _controller.index + 1;
        //     });
        //   },
        // ),
        centerTitle: true,
        bottom: TabBar(
          tabs: list,
          controller: _controller,
        ),
      ),

      body: Column(children: [
        SizedBox(
          height: 695,
          child: Container(
              padding: const EdgeInsets.fromLTRB(20, 20, 20, 0),
              child: TabBarView(
                controller: _controller,
                children: [
                  const Panel(),
                  const Func(),
                  ListView.separated(
                    separatorBuilder: (context, index) {
                      return const Divider(
                        height: 0,
                      );
                    },
                    itemCount: Provider.of<DoorModel>(context).logs.length,
                    itemBuilder: (BuildContext context, int index) {
                      const dtLen = 'yyyy-MM-dd HH:mm:ss'.length;
                      final log = Provider.of<DoorModel>(context).logs[index];
                      return ListTile(
                        title: Text(
                          log.substring(0, log.length - dtLen),
                        ),
                        subtitle: Text(log.substring(log.length - dtLen)),
                        trailing: Text(Dt.format(
                            DateTime.parse(log.substring(log.length - dtLen)))),
                      );
                    },
                  ),
                  // Text('4'),
                ],
              )),
        ),
        Expanded(
          child: Material(
              shadowColor: Colors.black,
              elevation: 60.0,
              //背景色
              color: Colors.grey[200],
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const Text('版本：1.0.0'),
                    Row(
                      children: [
                        IconButton(
                            tooltip: "连接安卓设备",
                            onPressed: () {
                              Box.deviceCommand();
                            },
                            color: const Color.fromARGB(255,13,110,253).withAlpha(30),
                            padding: const EdgeInsets.only(bottom: 5),
                            icon: const Icon(Icons.usb)),
                        IconButton(
                            tooltip: "安卓返回桌面",
                            onPressed: () {
                              Box.deviceDesk();
                            },
                            color: const Color.fromARGB(255,13,110,253).withAlpha(30),
                            padding: const EdgeInsets.only(bottom: 5),
                            icon: const Icon(Icons.computer)),
                        IconButton(
                            tooltip: "启动安卓程序（安卓端手动开门程序）",
                            onPressed: () {
                              Box.deviceLaunch();
                            },
                            color: const Color.fromARGB(255,13,110,253).withAlpha(30),
                            padding: const EdgeInsets.only(bottom: 5),
                            icon: const Icon(Icons.tablet_android)),
                      ],
                    ),
                    GestureDetector(
                      onDoubleTap: () {
                        // print('双击执行');R
                        // Info.snackbarWithoutContext('双击执行力');
                        Mongo.uploadUserczhs();
                      },
                      child: IconButton(
                        tooltip:
                            Provider.of<DoorModel>(context).userczhs.isEmpty
                                ? '点击上传今天的交路计划'
                                : '今天交路计划已加载完毕',
                        padding: const EdgeInsets.only(bottom: 5),
                        onPressed: () async {
                          await Provider.of<DoorModel>(context, listen: false)
                              .getUserczhs();
                        },
                        icon: Icon(Icons.cloud,
                            color:
                                Provider.of<DoorModel>(context).userczhs.isEmpty
                                    ? Colors.red
                                    : Colors.green),
                      ),
                    ),
                  ])),
        )
      ]),

      // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
